package com.qdsgjsfk.vision.ui;

import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.Toast;

import com.qdsgjsfk.vision.R;
import com.qdsgjsfk.vision.base.BaseApplication;
import com.qdsgjsfk.vision.util.QrConfigUtil;
import com.qdsgjsfk.vision.util.UtilString;
import com.rest.business.RestProxy;
import com.rest.client.SSLSocketClient;
import com.rest.response.QualifiedResponse;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.util.Objects;

import butterknife.BindView;
import butterknife.OnClick;
import cn.bertsir.zbar.Qr.ScanResult;
import cn.bertsir.zbar.QrConfig;
import cn.bertsir.zbar.QrManager;
import cn.bertsir.zbar.view.ScanLineView;
import io.reactivex.Observer;
import io.reactivex.disposables.Disposable;
import jz.joyoung.robot.util.LogUtil;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

import com.qdsgjsfk.vision.Common;
import com.qdsgjsfk.vision.base.BaseActivity;
import com.qdsgjsfk.vision.service.SocketService;
import com.qdsgjsfk.vision.ui.fragment.StudentListFragment;
import com.qdsgjsfk.vision.util.DpUtil;
import com.qdsgjsfk.vision.util.NetUtil;

import util.PreferencesHelper;
import util.ServiceUtil;

/**
 * 学生列表页
 * Created by HP on 2018/10/7.
 */

public class StudentListActivity extends BaseActivity {

    @BindView(R.id.timeline_tablayout)
    TabLayout mTabLayout;
    @BindView(R.id.timeline_viewpager)
    ViewPager mViewPager;

    @BindView(R.id.title)
    RelativeLayout title;

    @BindView(R.id.btn_add)
    ImageView btn_add;
    @BindView(R.id.btn_scan)
    ImageView btn_scan;


    String taskId, className, classId, orgId, classYear;
    int prefix;

    public static int REQUEST_CODE_SCAN = 1;
    private String[] mActions = new String[]{Common.ACTION_SERVICE_STATUS_SUCCESS,
            Common.ACTION_SERVICE_STATUS_FAILED,
    };


    @Override
    protected void initViews() {
        mViewPager.setAdapter(new StudentListAdapter(this, getSupportFragmentManager()));
        mTabLayout.setupWithViewPager(mViewPager);
        mTabLayout.setTabMode(TabLayout.MODE_FIXED);
        mTabLayout.setTabGravity(TabLayout.GRAVITY_FILL);

        mViewPager.setCurrentItem(0);
        Objects.requireNonNull( mTabLayout.getTabAt( 0 ) ).select();
        title.bringToFront();
        if (PreferencesHelper.getInstance().getInt(StudentListActivity.this, "perm") == 3) {
            btn_add.setVisibility(View.GONE);
            RelativeLayout.LayoutParams layoutParams = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
            layoutParams.addRule(RelativeLayout.ALIGN_PARENT_RIGHT, RelativeLayout.TRUE);
            layoutParams.addRule(RelativeLayout.CENTER_VERTICAL, RelativeLayout.TRUE);
            layoutParams.setMargins(0, 0, DpUtil.dip2px(StudentListActivity.this, 20), 0);
            btn_scan.setLayoutParams(layoutParams);
        }
    }

    @Override
    protected void initData() {
        classId = getIntent().getStringExtra("classId");
        taskId = getIntent().getStringExtra("taskId");
        orgId = getIntent().getStringExtra("orgId");
        classYear = getIntent().getStringExtra("classYear");
        prefix = getIntent().getIntExtra("prefix", -1);
        className = getIntent().getStringExtra("className");

        if (!ServiceUtil.isServiceExisted(this, "com.qdsgjsfk.vision.service.SocketService")) {
            stopService(new Intent(this, SocketService.class));
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                startForegroundService(new Intent(this, SocketService.class));
            } else {
                startService(new Intent(this, SocketService.class));
            }
        }
    }

    @Override
    protected int getLayoutResource() {
        return R.layout.activity_student_list;
    }


    class StudentListAdapter extends FragmentPagerAdapter {
        private static final int PAGE_COUNT = 3;

        private Context mContext;

        public StudentListAdapter(Context context, FragmentManager fm) {
            super(fm);
            this.mContext = context;
        }

        @Override
        public Fragment getItem(int position) {
            int type;
            switch (position) {
                case 0:
                    type = 0;
                    break;
                case 1:
                    type = 1;
                    break;
                case 2:
                    type = 2;
                    break;
                default:
                    type = -1;
                    break;
            }
            return StudentListFragment.newInstance(type, classId, taskId);
        }

        @Override
        public int getCount() {
            return PAGE_COUNT;
        }

        @Override
        public CharSequence getPageTitle(int position) {
            switch (position) {
                case 0:
                    return "全部";
                case 1:
                    return "视力未查";
                case 2:
                    return "屈光未查";
                default:
                    return "";
            }
        }

    }

    @OnClick(R.id.btn_add)
    void btn_add() {
        Bundle bundle = new Bundle();
        bundle.putString("classId", classId);
        bundle.putString("taskId", taskId);
        bundle.putString("orgId", orgId);
        bundle.putString("gradeName", className);
        bundle.putString("classYear", classYear);
        bundle.putInt("prefix", prefix);
        startActivity(AddStudentActivity.class, bundle);
    }

    @OnClick(R.id.btn_scan)
    void btn_scan() {
        QrManager.getInstance().init(QrConfigUtil.getQrConfig()).startScan(this, result -> {
            Log.e("onScanSuccess---", result.getContent());
//                Toast.makeText( getApplicationContext(), "内容：" + result.getContent()
//                        + "  类型：" + result.getType(), Toast.LENGTH_SHORT ).show();
            if (!UtilString.isEmpty(result.getContent())) {
                try {
                    scanQRCode(result.getContent());
//                    JSONObject obj = new JSONObject(content);
//                    getTaskWorker(obj.optString("taskId"), obj.optString("studentId"));
                } catch (Exception e) {
                    Toast.makeText(StudentListActivity.this, "二维码识别失败", Toast.LENGTH_SHORT).show();
                }
            }
        } );
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        // 扫描二维码/条码回传
        if (requestCode == REQUEST_CODE_SCAN && resultCode == RESULT_OK) {
//            if (data != null) {
//                String content = data.getStringExtra( Constant.CODED_CONTENT );
//                try {
//                    scanQRCode( content );
////                    JSONObject obj = new JSONObject(content);
////                    getTaskWorker(obj.optString("taskId"), obj.optString("studentId"));
//                } catch (Exception e) {
//                    Toast.makeText( this, "二维码有误", Toast.LENGTH_SHORT ).show();
//                }
//
//            }
        }
    }

    private void scanQRCode(String url) {
        System.out.println(url);
        OkHttpClient okHttpClient = new OkHttpClient.Builder().sslSocketFactory( SSLSocketClient.getSSLSocketFactory())
                .hostnameVerifier(SSLSocketClient.getHostnameVerifier())
                .build();
        final Request request = new Request.Builder()
                .url(url)
                .addHeader("Authorization", PreferencesHelper.getInstance().getString(this, "token"))
                .get()//默认就是GET请求，可以不写
                .build();
        Call call = okHttpClient.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {

            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                try {
                    Log.e("二维码---", response + "");
                    JSONObject obj = new JSONObject(response.body().string());
                    JSONObject json = new JSONObject(obj.optString("data"));
                    String tid = json.optString("tid");
                    String sid = json.optString("sid");
                    int type = json.optInt("type");
                    Log.e("二维码type---", type + "");
                    if (type == 10) {
                        Intent intMain;
                        LogUtil.e( "配置其他项" + BaseApplication.isShowOther );
                        if (BaseApplication.isShowAxis || BaseApplication.isShowOther) {
                            intMain = new Intent( getApplicationContext(), StudentDetailOtherActivity.class );
                        } else {
                            intMain = new Intent( getApplicationContext(), StudentDetailActivity.class );
                        }
                        Bundle bd = new Bundle();
                        bd.putString("studentId", sid);
                        bd.putString("taskId", taskId);
                        intMain.putExtras(bd);
                        startActivity(intMain);

                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }

            }
        });

    }

    @Override
    protected void onResume() {
        super.onResume();

        LogUtil.e("serviceStuList---" + ServiceUtil.isServiceExisted(this, "com.qdsgjsfk.vision.service.SocketService"));


    }
//    private void getTaskWorker(final String taskId,final String studentId){
//        RestProxy.getInstance().getTaskWorkers(PreferencesHelper.getInstance().getString(this, "token"), taskId, new Observer<TaskWorkerResponse>() {
//            @Override
//            public void onSubscribe(Disposable d) {
//
//            }
//
//            @Override
//            public void onNext(TaskWorkerResponse taskWorkerResponse) {
//                for(String s : taskWorkerResponse.data.taskWorkerIds){
//                    if (PreferencesHelper.getInstance().getString(StudentListActivity.this,"userId").equals(s)||PreferencesHelper.getInstance().getInt(StudentListActivity.this,"perm") == 1){
//                        Intent intMain = new Intent(getApplicationContext(), StudentDetailActivity.class);
//                        Bundle bd = new Bundle();
//                        bd.putString("studentId", studentId);
//                        bd.putString("taskId",taskId);
//                        intMain.putExtras(bd);
//                        startActivity(intMain);
//                        return;
//                    }
//                }
//                Toast.makeText(StudentListActivity.this, "权限不足", Toast.LENGTH_SHORT).show();
//            }
//
//            @Override
//            public void onError(Throwable e) {
//
//            }
//
//            @Override
//            public void onComplete() {
//
//            }
//        });
//    }

}
